<!-- 成员 -->

<template>
  <div class="marginBottom">
    <MajorTitle title="群组成员" />

    <BtnPrimary title="新增" :disabled="isShow" class="marginBottom" @click="toOpen" />

    <WebTable ref="table" :list="one.userContent" noPage>
      <RowText label="人员名称" bind="userName" />
      <RowTree :label="`所属${CORE.MAP.ORGAN}`" bind="organizationId" :dict="CORE.ORGAN.DICT" :minWidth="160" />
      <RowStatus label="成员类型" bind="userType" :dict="DICT.USER_TYPE" />
      <RowOperate :btns="['del']" :onDel="todel" :width="120" />
    </WebTable>

    <EasyModal v-model="easyVisible" title="选择用户" large @submit="toSubmit" @close="toReset">
      <ChooseUser :obj="obj" bind="userList" idKey="uaaUserId" />
    </EasyModal>
  </div>
</template>

<script>
// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'

// ============================== 导出组件 ============================== //

export default {
  /**
   * 名称定义 (实际使用名称)
   */
  name: 'MyMember',

  /**
   * 混入列表 (配置选项合并)
   */
  mixins: [CORE.mixWeb()],

  /**
   * 状态数据 (函数返回对象)
   */
  data() {
    return {
      easyVisible: false, // 弹窗是否可见
      obj: { userList: [] }, // 数据对象
    }
  },

  /**
   * 监听属性 (深度 deep 首次 immediate)
   */
  watch: {
    /**
     * 监听弹窗可见
     */
    easyVisible(visible) {
      visible && this.toReset()
    },

    /**
     * 监听负责人选择
     */
    'one.principalId'(id) {
      const users = this.one.userContent || []
      this.one.userContent = users.map((item) => ({ ...item, userType: item.userId === id ? 2 : 1 }))
    },
  },

  /**
   * 本地方法 (轻量重要在前)
   */
  methods: {
    /**
     * 弹窗
     */
    toOpen() {
      this.easyVisible = true
    },

    /**
     * 提交
     */
    toSubmit() {
      const { userList } = this.obj
      this.easyVisible = false
      this.one.userContent = userList.map((item) => {
        const organId = item.organId.at(0) || ''
        const organ = CORE.ORGAN.MAP[organId] || {}
        const userType = item.uaaUserId === this.one.principalId ? 2 : 1
        return {
          userId: item.uaaUserId,
          userName: item.name,
          userPhone: item.phone,
          organizationId: organId,
          organizationName: organ.name || '',
          userType,
        }
      })
    },

    /**
     * 重置
     */
    toReset() {
      const { userContent = [] } = this.one
      const userList = userContent.map((item) => ({
        uaaUserId: item.userId,
        name: item.userName,
        phone: item.userPhone,
        organId: [item.organizationId],
      }))
      this.obj = { userList }
    },

    /**
     * 清除
     */
    toClear() {
      this.obj = { userList: [] }
    },

    /**
     * 删除
     */
    todel(row) {
      const index = this.one.userContent.findIndex(item => item.userId === row.userId)
      index >= 0 && this.one.userContent.splice(index, 1)
    },
  },
}
</script>
